/**
 * @author:ϡ��
 * @time:����3:24:18
 * @filename:UserDAOImpl.java
 */
package ssh.rice.self.daoimpl;

import java.util.List;
import java.util.Set;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;

import ssh.rice.self.dao.UserDao;
import ssh.rice.self.entity.Area;
import ssh.rice.self.entity.User;
import ssh.rice.self.util.HibernateUtils;

public class UserDAOImpl implements UserDao {
	private HibernateUtils hibernateUtils;

	public void setHibernateUtils(HibernateUtils hibernateUtils) {
		this.hibernateUtils = hibernateUtils;
	}

	/**
	 * hibernate實現創建表格
	 */
	public void createTabel() {
		Configuration configuration = new Configuration().configure();
		SchemaExport sExport = new SchemaExport(configuration);
		sExport.create(true, true);
	}

	public int selectWhere(User user) {

		int login_id = -1;
		String hql = "from User where username = ? and password = ?";
		Session session = hibernateUtils.getSession();
		Transaction transaction = session.beginTransaction();
		try {
			Query query = session.createQuery(hql);
			query.setString(0, user.getUsername());
			query.setString(1, user.getPassword());
			@SuppressWarnings("unchecked")
			List<User> list = (List<User>) query.list();
			if (list.size() != 0) {
				login_id = list.get(0).getUid();
			}
			transaction.commit();
		} catch (Exception e) {
			// TODO: handle exception
			if (transaction != null) {
				transaction.rollback();
			}
		} finally {
			hibernateUtils.closeSession(session);
		}
		return login_id;
	}

	/**
	 * hibernate���F��Ӕ���
	 */
	public void add_OneToOne(User user) {
		// Transaction transaction = null;
		// Session session = null;
		// session = HibernateUtils.getSession();
		// transaction = session.beginTransaction();
		// try {
		// session.save(user);
		// transaction.commit();
		// } catch (Exception e) {
		// transaction.rollback();
		// } finally {
		// HibernateUtils.closeSession(session);
		// }
	}

	/**
	 * @Title: getAreas
	 * @Description: 返回用户关注地区
	 * @param uid
	 * @return
	 */
	public Set<Area> getAreas(int uid) {
		Set<Area> set = null;
		Session session = hibernateUtils.getSession();
		Transaction tx = session.beginTransaction();
		try {
			User user = (User) session.get(User.class, uid);
			set = user.getAreas();
			tx.commit();
		} catch (Exception e) {
			tx.rollback();
		} finally {
			// hibernateUtils.closeSession(session);
		}
		return set;
	}
}
